package com.lims.admin.action;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javacommon.base.BaseStruts2Action;

import cn.org.rapid_framework.page.Page;

import com.lims.admin.model.*;
import com.lims.admin.service.RoleManager;
import com.lims.admin.service.UserManager;
import com.lims.admin.vo.query.UserQuery;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
/**
 * @author zzh
 */
@SuppressWarnings({"serial","unchecked"})
public class UserRoleAction extends BaseStruts2Action implements Preparable,ModelDriven{

	protected static final String LIST_JSP= "/pages/admin/UserRole/list.jsp";
	protected static final String ROLELIST_JSP = "/pages/admin/UserRole/roleList.jsp";
	//redirect paths,startWith: !
	protected static final String LIST_ACTION = "!/pages/admin/UserRole/list.do";
	
	public void prepare() throws Exception {}

	public Object getModel() {return null;}

	private UserManager userManager;
	private RoleManager roleManager;
	private String uids;
	private String rids;
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}
	
	public void setUids(String uids) {
		this.uids = uids;
	}

	public void setRids(String rids) {
		this.rids = rids;
	}

	public String getUids() {
		return uids;
	}

	public String getRids() {
		return rids;
	}

	/** 执行搜索 */
	public String list() {
		UserQuery query = newQuery(UserQuery.class,null);
		Page page = userManager.findPage(query);
		savePage(page,query);
		return LIST_JSP;
	}
	
	/**
	 * 取得角色
	 * @return
	 */
	public String roleList(){
		if(isNullOrEmptyString(uids)) return ROLELIST_JSP;
		HttpServletRequest request = this.getRequest();
		if(uids.indexOf(",")==-1) {
			List<Role> roles = userManager.findRoleByUserId(uids);
			request.setAttribute("selectedRoles", roles);
		}
		List<Role> roleAll = roleManager.findAll();
		request.setAttribute("roleList", roleAll);
		return ROLELIST_JSP;
	}
	
	/**
	 * 保存角色给用户
	 * @return
	 */
	public String saveRolesToUsers(){
		List<User> users = this.userManager.findUsersByIds(uids);
		List<Role> roles = this.roleManager.findRolesByIds(rids);
		for (Iterator iterator = users.iterator(); iterator.hasNext();) {
			User user = (User) iterator.next();
			user.setRoles(roles);
			this.userManager.saveOrUpdate(user);
		}
		HttpServletRequest request = this.getRequest();
		request.setAttribute("selectedRoles", roles);
		List<Role> roleAll = roleManager.findAll();
		request.setAttribute("roleList", roleAll);
		request.setAttribute("saveMsg", true);
		return ROLELIST_JSP;
	}

}
